require "fileutils"

require "lib/formats"
require "lib/cue"
require "lib/converters"
require "lib/wave"
require "lib/wave_extractor"

module MediaTools
  
  class Splitter
    def split(source_track, source_cue, dest_path)
      processing_path = File.join(dest_path, ".processing")
      source_wav_path = File.join(processing_path, "source.wav")

      FileUtils.rm_r processing_path, :force => true, :secure => true
      FileUtils.mkdir processing_path
      
      begin
        source_container = ContainerFactory.container_for_file(source_track)
        converter = ConverterFactory.create_converter(source_container, Containers::WavContainer.new { |cnt| cnt.format = Formats::PcmWavFormat.matcher})
        converter.convert(source_track, source_wav_path)

        cue_parser = Cue::CueParser.new
        open(source_cue, "r") do |io|
          cue_parser.parse io
        end

        pcm_format = ContainerFactory.container_for_file(source_wav_path).format
        open(source_wav_path, "r") do |io|

          range_start = 0
          index = 1
          extract_track = lambda do |prev_track, track|
            if prev_track
              end_frames = track ? track.offset.to_frames : File.size(source_wav_path)
              range_end = (pcm_format.sample_rate * (end_frames / 75.0)).round

              fname = File.join(dest_path, "#{index} - #{prev_track.title || 'track'}.wav")
              io.rewind
              open(fname, "w") do |out_io|
                PcmWavExtractor.new.extract(io, out_io, range_start...range_end)
              end
              range_start = range_end

              index += 1
              fname
            end          
          end

          track_files = []
          prev_track = nil
          (cue_parser.tracks + [nil]).each do |track|
            track_files << extract_track.call(prev_track, track)
            prev_track = track
          end
          track_files
        end
      ensure
        FileUtils.rm_r processing_path, :force => true, :secure => true
      end
      
    end
  end
  
end